const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  entry: {
    popup: './src/popup/popup.js',
    // background: './src/background.js', // production
     background: './src/background-Dev.js', // dev
    'content-script': './src/content-script.js',
    'script/script_bundle': './src/script/script_bundle_entry.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    clean: true
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/, // 处理 .js 和 .jsx
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /\.css$/, // 处理 .css（如 popup.css）
        use: ['style-loader', 'css-loader', 'postcss-loader']
      },
      {
        test: /\.scss$/, // 处理 .scss（如 script1.scss）
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
          {
            loader: 'sass-loader',
            options: {
              api: 'modern-compiler', // 使用新 Sass API
              sassOptions: {
                silenceDeprecations: ['legacy-js-api'] // 禁用警告
              }
            }
          }
        ]
      },
      {
        test: /\.less$/, // 处理 .less（如 antd）
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true // 启用 Ant Design 的 Less
              }
            }
          }
        ]
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'imgs/[hash][ext]'
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/popup/index.html',
      filename: 'popup/index.html',
      chunks: ['popup']
    }),
    new CopyWebpackPlugin({
      patterns: [
        { from: 'manifest.json', to: 'manifest.json' },
        { from: 'src/lib', to: 'lib' },
        { from: 'src/imgs', to: 'imgs' }
      ]
    })
  ],
  mode: 'production',
  devtool: 'source-map',
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          format: {
            comments: false,
          },
          compress: true,
          mangle: true,
        },
        extractComments: false,
      })
    ]
  }
};